const app = getApp()
Page({
  data: {
    device_number: "temp", //设备代码
    temp: 0, //温度
    humi: 0, //湿度
    Light: 0, //光照度
    Soil: 0,  //土壤湿度
    stopRequest: false,
    requestInterval: null
  },

  // 读取设备代码
  Read_device_number: function (options) {
    var that = this;
    wx.getStorage({
      key: 'device_number',
      success: function (res) {
        //console.log('读取到的表单数据:', res.data);
        that.setData({
          device_number: res.data
        });
      },
      fail: function (res) {
        console.log('读取表单数据失败');
      }
    });
  },

  // 事件处理函数
  getinfo() {
    var that = this;
    if (this.data.stopRequest) {
      return
    }
    wx.request({
      url: "https://iot-api.heclouds.com/thingmodel/query-device-property?product_id=09ZW9ZUw80&device_name=" + this.data.device_number,
      header: {
        "Accept": "application/json, text/plain, */*",
        "authorization": "version=2022-05-01&res=userid%2F354693&et=2207232000&method=sha1&sign=i%2BVTsj0SJ0IX%2FKdobAaUlhFFC7A%3D"
      },
      method: "GET",
      query: {
        "product_id": "09ZW9ZUw80", //产品ID
        "device_name": this.data.device_number //设备名称
      },
      success: res => {
        if (!res.data.data || !res.data.data[3] || !res.data.data[3].value) {
          that.setData({
            stopRequest: true
          });
          clearInterval(that.data.requestInterval);
          wx.showModal({
            title: '错误',
            content: '设备代码输入错误，请检查后重试！',
            showCancel: false,
            confirmText: '确定',
            complete: (res) => {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        }else{
          that.setData({
            Light: res.data.data[3].value,
            humi: res.data.data[0].value,
            temp: res.data.data[5].value,
            Soil: res.data.data[4].value
          })
        }
        //console.log("获取成功",res);
      },
      fail: err => {
        console.log("获取失败", err);
      }
    });
  },

  switchChange: function (e) {
    if (e.detail.value) {
      //按钮发送命令控制硬件
      wx.request({
        url: "https://iot-api.heclouds.com/thingmodel/set-device-desired-property?product_id=09ZW9ZUw80&device_name=" + this.data.device_number,
        method: 'POST',
        header: {
          "authorization": "version=2022-05-01&res=userid%2F354693&et=2207232000&method=sha1&sign=i%2BVTsj0SJ0IX%2FKdobAaUlhFFC7A%3D"
        },
        data: {
          "product_id": "09ZW9ZUw80",
          "device_name": this.data.device_number,
          "params": {
            "led": true /* 使用传入的ledValue设置LED的状态 */
          }
        },
        success: res => {
          //console.log("成功",res)
        }
      });
    } else {
      //按钮发送命令控制硬件
      wx.request({
        url: "https://iot-api.heclouds.com/thingmodel/set-device-desired-property?product_id=09ZW9ZUw80&device_name=" + this.data.device_number,
        method: 'POST',
        header: {
          "authorization": "version=2022-05-01&res=userid%2F354693&et=2207232000&method=sha1&sign=i%2BVTsj0SJ0IX%2FKdobAaUlhFFC7A%3D"
        },
        data: {
          "product_id": "09ZW9ZUw80",
          "device_name": this.data.device_number,
          "params": {
            "led": false /* 使用传入的ledValue设置LED的状态 */
          }
        },
        success: res => {
          //console.log("成功",res)
        }
      });
    }
  },

  onLoad() {
    var that = this;
    setInterval(function () {
      that.getinfo();
    }, 1000)
  },

  // 登录判断
  onShow() {
    var that = this;
    this.Read_device_number();
    if (app.globalData.isLogin) {
      this.setData({
        isLogin: true
      })
      this.setData({
        userInfo: app.globalData.userInfo,
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '还未登录，请先登录！',
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            app.$util.switchTabTo("/pages/user/user");
          }
        }
      })
      this.setData({
        isLogin: false
      })
    }
    if (this.data.isLogin) {
      wx.cloud.callFunction({
        name: "db",
        data: {
          $url: "getUserInfo"
        }
      }).then(res => {
        if (res.result.code) {
          app.$db.set('userInfo', res.result.userInfo);
          this.setData({
            userInfo: res.result.userInfo,
            nickName: res.result.userInfo.nickName
          })
          app.globalData.userInfo = res.result.userInfo
        }
      })
    }
  }
})